package sivan.service;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import sivan.domain.Person;

import javax.sql.DataSource;
import java.sql.Types;

/**
 * Created by sivan on 2019/3/27.
 */
@Service
public class PersonService implements BeanFactoryAware {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void init(){
        System.out.println("PersonService初始化调用！！！！！！！！！！！！！！");
    }

    public PersonService() {
        System.out.println("初始化PersonService类！！！！！！！！！！！！！！！");
    }

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Transactional
    public void save(Person person) {
        this.update("qinglaopo",1);
        System.out.println("进行了添加操作==============");
        jdbcTemplate.update("INSERT INTO Person VALUES (?,?,?,?)", new Object[]{
                person.getId(), person.getUserName(), person.getAge(), person.getMobilePhone()
        }, new int[]{Types.INTEGER, Types.VARCHAR, Types.INTEGER, Types.VARCHAR});
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void update(String userName, int id) {
        System.out.println("更新数据操作。。。。。。。。。。。。");
        jdbcTemplate.update("UPDATE Person SET userName=? WHERE id = ?", new Object[]{
                userName, id
        }, new int[]{Types.VARCHAR, Types.INTEGER});
        throw new RuntimeException("运行时异常");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println(beanFactory);
    }
}
